// Created by WXX on 2021/10/6 14:25
#include <iostream>
#include <vector>

using namespace std;

/**
 * 执行用时：12 ms, 在所有 C++ 提交中击败了28.51%的用户
 * 内存消耗：9.1 MB, 在所有 C++ 提交中击败了46.15%的用户
 */
class Solution {
public:
    int surfaceArea(vector<vector<int>>& grid) {
        int res = 0;
        int n = grid.size();

        // 计算上下面的面积
        int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 0) continue;
                res += 2;
                for (int d = 0; d < 4; d++) {
                    int a = i + dx[d], b = j + dy[d];
                    if (a >= 0 && a < n && b >= 0 && b < n) {
                        res += max(0, grid[i][j] - grid[a][b]);
                    } else res += grid[i][j];  // 说明在边界
                }
            }

        return res;
    }
};

int main() {

    vector<vector<int>> grid = {
            {1, 2},
            {3, 4}
    };
    cout << Solution().surfaceArea(grid) << endl;  // 34

    return 0;
}
